package com.example.edianzu.somur.module.exercise;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.edianzu.somur.MainActivity;
import com.example.edianzu.somur.R;
import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.api.constans.AppContents;
import com.example.edianzu.somur.api.manager.APIManager;
import com.example.edianzu.somur.module.exercise.adapter.ExerciseAdapter;
import com.example.edianzu.somur.module.exercise.bean.BannerInfo;
import com.example.edianzu.somur.module.exercise.bean.ExerciseInfo;
import com.example.edianzu.somur.module.health.adapter.HealthAdapter;
import com.example.edianzu.somur.module.mine.activity.ReportActivity;
import com.example.edianzu.somur.utils.content.CallPhone;
import com.example.edianzu.somur.utils.view.BaseFragment;
import com.example.edianzu.somur.utils.view.GlideRoundTransform;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExerciseFragment extends BaseFragment {

    @BindView(R.id.fragment_exercise_title)
    AppCompatTextView fragmentExerciseTitle;
    @BindView(R.id.fragment_exercise_banner)
    Banner banner;
    @BindView(R.id.fragment_exercise_phone)
    AppCompatTextView fragmentExercisePhone;
    /*@BindView(R.id.fragment_exercise_name)
    TextView fragmentExerciseName;
    @BindView(R.id.fragment_exercise_location)
    TextView fragmentExerciseLocation;
    @BindView(R.id.fragment_exercise_exercise)
    TextView fragmentExerciseExercise;
    @BindView(R.id.fragment_exercise_view_0)
    FrameLayout fragmentExerciseView0;
    @BindView(R.id.fragment_exercise_content)
    TextView fragmentExerciseContent;
    @BindView(R.id.fragment_exercise_view_1)
    FrameLayout fragmentExerciseView1;
    @BindView(R.id.fragment_exercise_invitation)
    TextView fragmentExerciseInvitation;
    @BindView(R.id.fragment_exercise_view_2)
    FrameLayout fragmentExerciseView2;
    @BindView(R.id.fragment_exercise_salon)
    TextView fragmentExerciseSalon;*/
    Unbinder unbinder;
    @BindView(R.id.fragment_exercise_RecyclerView)
    RecyclerView fragmentExerciseRecyclerView;
    //    @BindView(R.id.fragment_exercise_banner)
//    XBanner fragmentExerciseBanner;
    private LoginInfo loginInfo;
    private List<String> imgPath = new ArrayList<>();
    private static final String TAG = "ExerciseFragment";
    private List<ExerciseInfo.DataBean> data;
    private ExerciseAdapter adapter;

    /*java.lang.ArithmeticException: divide by zero (2015-06-01 14:15:29)转载▼
如果遇见了这个错误，您务必要检查下您的代码里是不是会有机会出现“除数不能是零”，也就是说不付合数学方法！即1/0是错误的！*/
    public ExerciseFragment() {
        // Required empty public constructor
    }

    //Fragment中的onAttach方法
    //通过强转成宿主activity，就可以获取到传递过来的数据
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        loginInfo = ((MainActivity) activity).getLoginInfo();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        APIManager.getApiManagerInstance().getExerciseInfo(new Observer<ExerciseInfo>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull ExerciseInfo exerciseInfo) {

                if (exerciseInfo.getStatus() == AppContents.STATUS) {

                    data = exerciseInfo.getData();

//                    L.d(TAG, "onNext: exerciseInfo.getStatus() == AppContents.STATUS"+data.size());

//                        setTitle();

                    adapter = new ExerciseAdapter(data);
                    fragmentExerciseRecyclerView.setAdapter(adapter);
                    adapter.setOnItemClickListener(new HealthAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClickListener(View view, int position) {

                            Intent intent=new Intent(getContext(), ReportActivity.class);
                            intent.putExtra("url", data.get(position).getUrl());
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        }, loginInfo != null ? loginInfo.getData().getCompany_id() : "null", 1);
    }

    @Override
    protected void initViewPagerFragment(List<String> title, List<Fragment> fragmentList) {

    }

    @Override
    protected boolean isLoadTopView() {
        return false;
    }

    @Override
    protected int setTopViewId() {
        return 0;
    }

    @Override
    protected int setLoadBottomViewId() {
        return 0;
    }

    @Override
    protected boolean isLoadBottomView() {
        return false;
    }

    @NonNull
    private HashMap<String, String> getStringStringHashMap() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("company_id", loginInfo.getData().getCompany_id() + "");

        Log.d(TAG, "getStringStringHashMap: " + loginInfo.getData().getCompany_id() + "");
        hashMap.put("type", 1 + "");
        return hashMap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_exercise, container, false);
        unbinder = ButterKnife.bind(this, view);

        fragmentExerciseRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));

        if (imgPath != null && imgPath.size() > 0) {

            banner.start();

//            initXBanner();
        } else {

            initBanner();

            APIManager.getApiManagerInstance().getBannerInfo(new Observer<BannerInfo>() {
                @Override
                public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                }

                @Override
                public void onNext(@io.reactivex.annotations.NonNull BannerInfo bannerInfo) {

                    if (bannerInfo.getStatus() == AppContents.STATUS) {

                        for (int i = 0; i < bannerInfo.getData().size(); i++) {

                            imgPath.add(bannerInfo.getData().get(i).getImage_path());
                            Log.d(TAG, "size-----------"+bannerInfo.getData().size()+"-----------onResponse: " + bannerInfo.getData().get(i).getImage_path() + "url" + bannerInfo.getData().get(i).getUrl());
                        }

                        if (imgPath != null && imgPath.size() > 0) {

//                            initXBanner();

                            //设置图片集合
                            banner.setImages(imgPath);

                            //banner设置方法全部调用完毕时最后调用
                            banner.start();
                        }
                    }
                }

                @Override
                public void onError(@io.reactivex.annotations.NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            }, loginInfo != null ? loginInfo.getData().getCompany_id() : "null", 1);
        }


        if (data != null && data.size() > 0) {

//            setTitle();

            adapter = new ExerciseAdapter(data);
            fragmentExerciseRecyclerView.setAdapter(adapter);
            adapter.setOnItemClickListener(new HealthAdapter.OnItemClickListener() {
                @Override
                public void onItemClickListener(View view, int position) {

                    Intent intent=new Intent(getContext(), ReportActivity.class);
                    intent.putExtra("url", data.get(position).getUrl());
                    startActivity(intent);
                }
            });
        } else {



//            StringRequest stringList = new StringRequest(Request.Method.POST, APIRequest.ESERCISELIST_URL, new Response.Listener<String>() {
//
//                @Override
//                public void onResponse(String response) {
//
//                    ExerciseInfo exerciseInfo = JSON.parseObject(response, ExerciseInfo.class);
//                    if (exerciseInfo.getStatus() == 200) {
//
//                        data = exerciseInfo.getData();
//
//                        Log.d(TAG, "onResponse: " + data);
//
//                        setTitle();
//                    }
//                }
//            }, new Response.ErrorListener() {
//                @Override
//                public void onErrorResponse(VolleyError error) {
//
//
//                }
//            }) {
//                @Override
//                protected Map<String, String> getParams() throws AuthFailureError {
//
//                    return getStringStringHashMap();
//                }
//            };
//            stringList.setTag("exercise");
//            requestQueue.add(stringList);
        }

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        banner.startAutoPlay();
    }

    @Override
    public void onResume() {
        super.onResume();

//        fragmentExerciseBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();

        imgPath.clear();
        banner.stopAutoPlay();
//        fragmentExerciseBanner.stopAutoPlay();
    }

    /*private void initXBanner() {

        fragmentExerciseBanner.setData(imgPath,null);
        fragmentExerciseBanner.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {

                Glide.with(getContext()).load(imgPath.get(position)).transform(new GlideRoundTransform(getContext(), 10)).into(((ImageView) view));
            }
        });
        // 设置XBanner的页面切换特效
        fragmentExerciseBanner.setPageTransformer(Transformer.Default);
        // 设置XBanner页面切换的时间，即动画时长
        fragmentExerciseBanner.setPageChangeDuration(1000);
//        XBanner中某一项的点击事件
        fragmentExerciseBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {
                Toast.makeText(getActivity(), "点击了第" + (position + 1) + "张图片", Toast.LENGTH_SHORT).show();
            }
        });
    }*/

//    private void setTitle() {
//        if (data != null && data.size() > 0) {
//
//            switch (data.size()) {
//
//                case 1:
//
//                    fragmentExerciseContent.setText(data.get(0).getTitle());
//                    break;
//                case 2:
//
//                    fragmentExerciseContent.setText(data.get(0).getTitle());
//                    fragmentExerciseInvitation.setText(data.get(1).getTitle());
//                    break;
//                case 3:
//
//                    fragmentExerciseContent.setText(data.get(0).getTitle());
//                    fragmentExerciseInvitation.setText(data.get(1).getTitle());
//                    fragmentExerciseSalon.setText(data.get(2).getTitle());
//                    break;
//                default:
//                    break;
//            }
//        }
//    }

    private void initBanner() {

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(getContext()).load(path).transform(new GlideRoundTransform(getContext(), 50)).into(imageView);
            }
        });

//        设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(list_title);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3 * 1000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

                Toast.makeText(getActivity(), "点击了第" + (position + 1) + "张图片", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({/*R.id.fragment_exercise_content, R.id.fragment_exercise_invitation, R.id.fragment_exercise_salon,*/ R.id.fragment_exercise_phone})
    public void onViewClicked(View view) {

        Intent intent = new Intent();
        if (data != null && data.size() > 0) {

            switch (view.getId()) {
//                case R.id.fragment_exercise_content:
//
//                    intent.setClass(getContext(), ReportActivity.class);
//                    intent.putExtra("url", data.get(0).getUrl());
//                    startActivity(intent);
//                    break;
//                case R.id.fragment_exercise_invitation:
//
//                    if (data.size() == 2) {
//
//                        intent.setClass(getContext(), ReportActivity.class);
//                        intent.putExtra("url", data.get(1).getUrl());
//                        startActivity(intent);
//                    } else {
//
//                        intent.setClass(getContext(), ReportActivity.class);
//                        intent.putExtra("url", data.get(0).getUrl());
//                        startActivity(intent);
//                    }
//                    break;
//                case R.id.fragment_exercise_salon:
//
//                    if (data.size() == 3) {
//
//                        intent.setClass(getContext(), ReportActivity.class);
//                        intent.putExtra("url", data.get(2).getUrl());
//                        startActivity(intent);
//                    } else {
//
//                        intent.setClass(getContext(), ReportActivity.class);
//                        intent.putExtra("url", data.get(0).getUrl());
//                        startActivity(intent);
//                    }
//                    break;
                case R.id.fragment_exercise_phone:

                    CallPhone.call(fragmentExercisePhone.getText().toString(), getContext());
                    break;
            }
        }
    }
}
